package com.loong.musicdemo.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;

import com.loong.musicdemo.R;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 自动刷新账户信息
 */
public class AutoUpdateAccount extends Service {
    public AutoUpdateAccount() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        updateBackgroundImg();//更新背景图片
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int time = 60 * 60 * 1000;//一小时刷新一次
        long triggerAtTime = SystemClock.elapsedRealtime() + time;
        Intent i = new Intent(this, AutoUpdateAccount.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新背景图片
     */
    private void updateBackgroundImg() {
        String imgUrl = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOKHttpRequest(imgUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String imgBytes = Objects.requireNonNull(response.body()).string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateAccount.this).edit();
                editor.putString("bing_pic", imgBytes);
                editor.apply();
            }
        });
    }
}
